<script setup lang="ts">
defineComponent({ name: 'ArticleDetail' })
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { defineComponent, onBeforeUnmount, onMounted, reactive, ref, shallowRef, watch, } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import service from '../config/index';
const emit = defineEmits(['close', 'reSearch']);
const props = defineProps<{
    type: String,
    id: String,
    showDrawer: Boolean
}>();
const editorRef = shallowRef()
const editorKey = ref(0) // 强制重挂载用
const toolbarConfig = { excludeKeys: ['fullScreen', 'codeBlock', 'group-video'] }
const editorConfig = ref({
    readOnly: false,
    placeholder: '请输入正文内容...',
    MENU_CONF: {
        uploadImage: {
            customUpload(file, insertFn) {
                const formData = new FormData();
                formData.append('uploadFile', file);
                service.post('/image/upload', formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                })
                    .then(res => {
                        const imageUrl = res.data.url;
                        const altText = '';
                        const hrefLink = '';
                        insertFn(imageUrl, altText, hrefLink);
                    })
                    .catch(error => {
                        ElMessage.error(error?.response?.statusText || error?.message);
                    });
            }
        }
    }
})
const data = ref<{ title: string, metaTitle: string, metaDescription: string, terms: string, text: string, firstP: string }>({
    title: '',
    metaTitle: '',
    metaDescription: '',
    terms: '',
    text: '',
    firstP: ''
})
const options = ref([])
const languageOptions = ref([])
const siteOptions = ref([])
const allSiteOptions = ref([])
const accountNameOptions = ref([])
const ruleFormRef = ref<FormInstance>()

interface RuleForm {
    outShow: string
    articleCategoryId: string
    langId: number,
    accountId: number
    siteId: number

}

const ruleForm = ref<RuleForm>({
    outShow: '1',
    articleCategoryId: '',
    accountId: null,
    langId: null,
    siteId: null
})

const rules = reactive<FormRules<RuleForm>>({
    outShow: [
        { required: true, message: '', trigger: 'blur' },
    ],
    articleCategoryId: [{ required: true, message: '请选择文章分类', trigger: 'blur' }],
    langId: [{ required: true, message: '请选择语言', trigger: 'blur' }],
    accountId: [{ required: true, message: '请选择账户名称', trigger: 'blur' }],
    siteId: [{ required: true, message: '请选择所属网站', trigger: 'blur' }]
})


const getAccount = () => {
    service.get('/account/getAll')
        .then(response => {
            accountNameOptions.value = response?.data
            accountNameOptions.value.push({ id: -1, name: '其他' })
        })
        .catch(error => {
            ElMessage.error(error)
        });
}


const buildTree = (nodes, parentId = null) => {
    return nodes
        .filter(node => node.parentId === parentId)
        .map(node => {
            const children = buildTree(nodes, node.value);
            return {
                ...node,
                ...(children.length > 0 ? { children } : {})
            };
        });
}

const getArticleCategory = () => {
    service.get('/article/allCategory')
        .then(response => {
            const treeData = response.data?.map(item => ({
                label: item.name,
                value: item.id,
                parentId: item.parentId,
                alias: item.alias
            }));
            options.value = buildTree(treeData);
        })
        .catch(error => {
            ElMessage.error(error?.message || '提交失败！')
        });
}

const getlangCategory = () => {
    service.get('/lang/getAll')
        .then(response => {
            languageOptions.value = response?.data
        })
        .catch(error => {
            console.error('Error fetching data:', error);
        });
}

const handleSelectAccount = () => {
    const selectedAccountId = ruleForm.value.accountId
    if (selectedAccountId === null || selectedAccountId === undefined) {
        siteOptions.value = [...allSiteOptions.value]
        return
    }
    const filtered = allSiteOptions.value?.filter((item: any) => item.accountId == selectedAccountId) || []
    siteOptions.value = filtered
    const exists = filtered?.some((s: any) => s.id == ruleForm.value.siteId)
    if (!exists) {
        ruleForm.value.siteId = null
    }
}


const getSite = () => {
    service.get('/site/getAll')
        .then(response => {
            allSiteOptions.value = response?.data || []
            siteOptions.value = [...allSiteOptions.value]
        })
        .catch(error => {
            console.error('Error fetching data:', error);
        });
}

const handleClose = () => {
    emit('close');
    if (editorRef.value) {
        try { editorRef.value.destroy?.() } catch (e) { /* ignore */ }
        editorRef.value = null
    }
    editorKey.value++
    ruleForm.value = {
        outShow: '1',
        articleCategoryId: '',
        langId: null,
        siteId: null,
        accountId: null
    }
    data.value = {
        title: '',
        metaTitle: '',
        metaDescription: '',
        terms: '',
        text: '',
        firstP: ''
    }
}

const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}

const handleSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            const parser = new DOMParser();
            const doc = parser.parseFromString(data.value.text, 'text/html');
            // 2. 获取第一个 img 标签的 src
            const firstImg = doc.querySelector('img');
            const firstImgSrc = firstImg?.src; // 使用可选链防止报错
            console.log(firstImgSrc);
            service.post(props.type === 'add' ? '/article/add' : '/article/update', { ...ruleForm.value, ...data.value, articleCategoryId: typeof ruleForm.value.articleCategoryId === 'number' ? ruleForm.value.articleCategoryId : ruleForm.value.articleCategoryId?.[ruleForm.value.articleCategoryId?.length - 1], id: props.type === 'add' ? undefined : props.id, image: firstImgSrc || undefined })
                .then(response => {
                    ElMessage.success('提交成功！')
                    handleClose()
                    emit('reSearch')
                })
                .catch(error => {
                    ElMessage.error(error || '提交失败！')
                });
        } else {

        }
    })
}

watch(() => props.showDrawer, () => {
    if (!props.showDrawer) return
    // 每次打开或切换文章，销毁旧实例并强制重挂载
    if (editorRef.value) {
        try { editorRef.value.destroy?.() } catch (e) { /* ignore */ }
        editorRef.value = null
    }
    editorKey.value++
    data.value.text = ''
    if (props.type !== 'add') {
        service.post('/article/detail', { id: props.id })
            .then(response => {
                if (response?.data) {
                    ruleForm.value = {
                        articleCategoryId: response.data?.articleCategoryId,
                        outShow: response.data?.outShow,
                        langId: response.data?.langId,
                        siteId: response.data?.siteId,
                        accountId: response.data?.accountId
                    }
                    data.value = {
                        title: response.data?.title,
                        metaTitle: response.data?.metaTitle,
                        metaDescription: response.data?.metaDescription,
                        terms: response.data?.terms,
                        text: (response.data?.text || ''),
                        firstP: response.data?.firstP
                    }
                }
            })
            .catch(error => {
                console.error('Error fetching data:', error);
            })
    }
}, { immediate: true })

onMounted(() => {
    getArticleCategory()
    getlangCategory()
    getSite()
    getAccount()
})

onBeforeUnmount(() => {
    if (editorRef.value) {
        try { editorRef.value.destroy?.() } catch (e) { /* ignore */ }
        editorRef.value = null
    }
})

</script>

<template>
    <div class="article-detail">
        <div
            style="display: flex; padding:16px 24px;border-bottom: 1px solid rgba(5, 5, 5, 0.06);background-color: #fff;justify-content: space-between;">
            <span style="display: flex; align-items: center;font-size: 20px;font-weight: 700;">添加文章</span>
            <div>
                <el-form ref="ruleFormRef" style="display: flex;flex: 1;align-items: center;gap: 15px;"
                    :model="ruleForm" :rules="rules" label-width="auto">
                    <el-form-item label="是否外显" prop="outShow">
                        <el-radio-group v-model="ruleForm.outShow" :disabled="props.type === 'check'">
                            <el-radio value="1" size="large" style="margin-right: 10px;">是</el-radio>
                            <el-radio value="0" size="large">否</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="分类" prop="articleCategoryId">
                        <el-cascader style="width: 170px;margin-right: 10px;" clearable
                            v-model="ruleForm.articleCategoryId" :options="options" placeholder="请选择文章分类"
                            :disabled="props.type === 'check'" />
                    </el-form-item>
                    <el-form-item label="账户" prop="accountId">
                        <el-select v-model="ruleForm.accountId" placeholder="请选择账户名称" style="width: 170px"
                            :disabled="props.type === 'check'" @change="handleSelectAccount">
                            <el-option v-for="item in accountNameOptions" :key="item.id" :label="item.name"
                                :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="网站" prop="siteId">
                        <el-select v-model="ruleForm.siteId" placeholder="请选择所属网站" style="width: 150px"
                            :disabled="props.type === 'check'">
                            <el-option v-for="item in siteOptions" :key="item.id" :label="item.siteName"
                                :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="语言" prop="langId">
                        <el-select v-model="ruleForm.langId" placeholder="请选择语言" style="width: 150px"
                            :disabled="props.type === 'check'">
                            <el-option v-for="item in languageOptions" :key="item.id" :label="item.langName"
                                :value="item.id" />
                        </el-select>
                    </el-form-item>
                </el-form>
            </div>
            <span style="display: flex; align-items: center;"> <el-button @click="handleClose">取消</el-button>
                <el-button class="submit-btn" @click="handleSubmit(ruleFormRef)"
                    v-if="props.type !== 'check'">提交</el-button></span>
        </div>
        <Toolbar
            style="border-bottom: 1px solid  rgba(5, 5, 5, 0.06);display: flex;justify-content: center;background-color: #fff;"
            :editor="editorRef" :defaultConfig="toolbarConfig" mode="default" />
        <div class="content-page">
            <div class="editor-container">
                <div class="title-container"><el-input :disabled="props.type === 'check'" class="title"
                        v-model="data.title" type="textarea" :autosize="{ minRows: 1.2 }" style="font-size: 28px;"
                        resize="none" placeholder="请输入文章标题" />
                </div>
                <div class="title-container"><el-input :disabled="props.type === 'check'" v-model="data.metaTitle"
                        :autosize="{ minRows: 3 }" type="textarea" resize="none" placeholder="请输入文章meta-title" />
                </div>
                <div class="title-container"><el-input :disabled="props.type === 'check'" v-model="data.metaDescription"
                        :autosize="{ minRows: 3 }" type="textarea" resize="none" placeholder="请输入文章meta-description" />
                </div>
                <div class="title-container"><el-input :disabled="props.type === 'check'" v-model="data.terms"
                        :autosize="{ minRows: 3 }" type="textarea" resize="none" placeholder="请输入文章terms" />
                </div>
                <div class="title-container"><el-input :disabled="props.type === 'check'" v-model="data.firstP"
                        :autosize="{ minRows: 3 }" type="textarea" resize="none" placeholder="请输入文章概览" />
                </div>
                <Editor :key="editorKey" disabled style="min-height: 800px; overflow-y: hidden;height: auto;"
                    v-model="data.text" :defaultConfig="editorConfig" mode="default" @onCreated="handleCreated" />
            </div>
        </div>

    </div>
</template>

<style lang="scss">
.article-detail {
    background-color: #f5f5f5;
    height: 100%;

    .w-e-modal {
        z-index: 999 !important;
        right: 0 !important;
    }

    .el-radio__input.is-checked+.el-radio__label {
        color: #1677ff;
    }

    .el-radio__input.is-checked .el-radio__inner {
        background: #1677ff;
        border-color: #1677ff;
    }

    .el-radio__input.is-checked+.el-radio__label {
        color: #000;
        font-weight: 600;
    }

    .submit-btn {
        background-color: #1677ff;
        color: #fff;
        box-shadow: 0 2px 0 rgba(5, 145, 255, 0.1);
    }

    .submit-btn:hover {
        background-color: #1677ff !important;
        color: #fff !important;
    }

    .submit-btn:active {
        background-color: #1677ff !important;
        color: #fff !important;
        border: none;
    }

    .el-button:focus {
        outline: none;
    }

    .content-page {
        height: calc(100% - 123px);
        background-color: #f5f5f5;
        overflow: auto;

        .editor-container {
            height: auto;
            width: 750px;
            margin: 30px auto 150px;
            background-color: #fff;
            padding: 20px 50px 50px;
            border: 1px solid #e8e8e8;
            box-shadow: 0 2px 10px #0000001f;

            .title-container {
                padding: 10px 0;
                border-bottom: 1px solid #e8e8e8;
            }
        }
    }

    .el-textarea__inner {
        box-shadow: none;
    }

    .el-textarea__inner.is-focus {
        box-shadow: none;
    }

    .el-textarea__inner:hover {
        box-shadow: none;
    }

    .title {
        .el-textarea__inner::placeholder {
            font-size: 30px;
        }
    }

    .el-form-item {
        margin-bottom: 0;
    }

    .el-form-item__label-wrap {
        align-items: center;
    }

    .el-form-item__label {
        font-weight: 700;
        color: #000;
    }

    .el-radio-group {
        flex-wrap: nowrap;
    }

    .el-textarea.is-disabled .el-textarea__inner {
        background-color: transparent;
        box-shadow: none;
    }
}
</style>
